import {config} from "../config";

const defaultTip = "获取数据失败"

// # 解构
class HTTP {

    request({url, data = {}, method = 'POST'}) {
        return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method)
        })
    }

    _request(url, resolve, reject, data = {}, method = 'POST') {
        wx.request({
            url: config.apiUrl + url,
            method: method,
            data: data,
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                'nioupversion': '1.0.0',
                "appkey": "123"
            },
            success: (res) => {

                const code = res.data.code.toString()

                if (code.startsWith('2')) {
                    resolve(res.data.data)
                } else {
                    reject()
                    const message = res.data.message
                    this._showMessage(message)
                }
            },
            fail: (err) => {
                reject()
                this._showMessage(err.data.message)
            }
        })

    }

    _showMessage(message) {

        wx.showToast({
            title: message || defaultTip,
            icon: "none"

        })

    }

}

export {HTTP}
